<template>
  <div class="page-leveladd">
    <pk-dialog :title="title" @confirm="confirm" @onClose="onClose" width="500px">
      <div class="mt-12 mb-12">
        <pk-form :formConfig="formConfig" labelPosition="top" ref="myForm"></pk-form>
      </div>
    </pk-dialog>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, onMounted } from 'vue'
import pkDialog from '@/components/pkui/pk-dialog/pk-dialog.vue'
import pkForm from '@/components/pkui/pk-form/pk-form.vue'
import { userCreate, userUpdate, dutiesGetList } from '@/api/api'
import { AES_Encrypt } from '@/utils/3des'
const emit = defineEmits(['confirm', 'onClose'])
const props = defineProps({
  curData: {
    type: Object,
    default: () => {}
  }
})
const title = ref('添加评委')
const myForm = ref(null)
const formConfig = ref([ 
  {
    label: '账号名(UID)',
    type: 'input',
    prop: 'account'
  },
  {
    label: '手机号码',
    type: 'input',
    prop: 'phone'
  },
  {
    label: '评委姓名',
    type: 'input',
    prop: 'username'
  },
  {
    label: '组名',
    type: 'select',
    prop: 'userDutiesId',
    options: []
  },   
  {
    label: '状态',
    type: 'radio',
    prop: 'status',
    options: [
      {
        label: '正常',
        value: 1
      },
      {
        label: '停用',
        value: 2
      }
    ]
  },  
])


const onClose = () => {
  emit('onClose')
}

const postAdd = (data) => {
  userCreate({
    ...data
  }).then(res => {
    emit('confirm')
  })
}

const postEdit = (data) => {
  let params = {
    ...data,
    id: props.curData.id
  }
  userUpdate(params).then(res => {
    emit('confirm')
  })
}

const confirm = () => {
  myForm.value.submitForm().then(res => {
    if (props.curData?.id) {
      postEdit(res)
    } else {
      postAdd(res)
    }
  })
}

const getDuties = () => {
  dutiesGetList({
    pageNum: 1,
    pageSize: 1000
  }).then(res => {
    formConfig.value[3].options = res.resData.map(item => {
      return {
        label: item.name,
        value: item.id
      }
    })
  })
}

const initStart = () => {
  if (props.curData?.id) {
    title.value = '编辑评委'
    myForm.value.setFormProp('phone', props.curData.phone)
    myForm.value.setFormProp('account', props.curData.account)
    myForm.value.setFormProp('username', props.curData.username)
    myForm.value.setFormProp('status', props.curData.status)
    myForm.value.setFormProp('userDutiesId', props.curData.userDutiesId)
  } else {
    title.value = '添加评委'
  }
  getDuties()
}
onMounted(() => {
  setTimeout(() => {
    initStart()
  }, 100)
})

</script>

<style lang="scss" scoped>

</style>